import { Flex, useColorModeValue } from '@chakra-ui/react';
import { useScroll } from 'ahooks';
import { useEffect, useState } from 'react';

const BackToTop = () => {
  const scroll = useScroll(document);
  const [show, setShow] = useState<boolean>(false);
  const bg = useColorModeValue('white', 'gray.800');
  const hover_bg = useColorModeValue('gray.800', 'gray.300');
  const color = useColorModeValue('gray.800', 'gray.300');
  const hover_color = useColorModeValue('white', 'gray.800');
  useEffect(() => {
    setShow(Boolean(scroll && scroll.top && scroll.top > 100));
  }, [scroll]);

  return (
    <>
      {show ? (
        <Flex
          h="12"
          w="12"
          cursor="pointer"
          position="fixed"
          right="8"
          bottom="20"
          shadow="md"
          zIndex="10"
          bg={bg}
          p={2}
          _hover={{
            bg: hover_bg,
          }}
          transitionDuration="0.6s"
          borderRadius="base"
          onClick={() => {
            window.scrollTo({
              top: 0,
              behavior: 'smooth',
            });
          }}
          sx={{
            svg: {
              color: color,
            },
            '&:hover svg': {
              color: hover_color,
            },
          }}
        >
          <svg viewBox="0 0 20 20">
            <polyline
              points="2 13 10 5 18 13"
              fill="none"
              stroke="currentColor"
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth="2"
            />
          </svg>
        </Flex>
      ) : null}
    </>
  );
};

export default BackToTop;
